<!DOCTYPE html>
<html lang="zh-cn">

<head>

  <meta content="text/html;charset=utf-8" http-equiv="content-type">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">

  <title>滑雪族 - 产品编辑</title>

  <!-- Bootstrap Core CSS -->
<!-- MetisMenu CSS -->
<!-- Custom CSS -->
<!-- Custom Fonts -->
  <!--webuploader 引入CSS-->
  <!-- Bootstrap DateRangePicker CSS -->
  <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
  <!-- WARNING: Respond.js doesn"t work if you view the page via file:// -->
  <!--[if lt IE 9]>
  <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
  <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
  <![endif]-->

    <link rel="stylesheet" href="/server/r/bower_components/bootstrap/dist/css/bootstrap.min.css" />
    <link rel="stylesheet" href="/server/r/bower_components/metisMenu/dist/metisMenu.min.css" />
    <link rel="stylesheet" href="/server/r/static/css/sb-admin-2_e507c2b.css" />
    <link rel="stylesheet" type="text/css" href="/server/r/bower_components/font-awesome/css/font-awesome.min.css" />
    <link type="text/css" rel="stylesheet" href="/server/r/static/css/hxz/common_2baa698.css" />
    <link rel="stylesheet" type="text/css" href="/server/r/bower_components/alertify/themes/alertify.core.css" />
    <link rel="stylesheet" type="text/css" href="/server/r/bower_components/alertify/themes/alertify.bootstrap.css" />
    <link rel="stylesheet" type="text/css" href="/server/r/bower_components/fex-webuploader/dist/webuploader.css" />
    <link type="text/css" rel="stylesheet" href="/server/r/vendor/umeditor/themes/default/css/umeditor.css" />
    <link rel="stylesheet" href="/server/r/bower_components/bootstrap-daterangepicker/daterangepicker.css" />
    <link type="text/css" rel="stylesheet" href="/server/r/bower_components/select2/dist/css/select2.min.css" />
</head>

<body>

<div id="wrapper">
  <input id="activity-id" type="hidden" value="${(activity.activityId)!''}"/>
  <input id="activity-type-id" type="hidden" value="${(activity.typeId)!''}">
  <#if episode??>
    <input id="episode-id" type="hidden" value="${(episode.episodeId)!''}"/>
    <input id="episode-status" type="hidden" value="${(episode.status)!''}"/>
    <input id="current-player-count" type="hidden" value="${(episode.playerCount)}"/>
  </#if>
  <input id="episode-meta-name" type="hidden" value="${filterRuler(activity.typeId,"episode_detail_title_head")!""}">
  <input id="voucher-send" type="hidden" value="0">
  <!-- Navigation -->
  <nav class="navbar navbar-default navbar-static-top" role="navigation" style="margin-bottom: 0">

    <div class="navbar-header">
  <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
    <span class="sr-only">Toggle navigation</span>
    <span class="icon-bar"></span>
    <span class="icon-bar"></span>
    <span class="icon-bar"></span>
  </button>
  <a class="navbar-brand" href="activity-list">滑雪族 管理</a>
</div>
<!-- /.navbar-header -->

<ul class="nav navbar-top-links navbar-right">
  <!-- /.dropdown -->
  <li class="dropdown">
    <a class="dropdown-toggle" data-toggle="dropdown" href="#">
      <i class="fa fa-user fa-fw"></i> <i class="fa fa-caret-down"></i>
    </a>
    <ul class="dropdown-menu dropdown-user">
      <li><a href="/manage/logout"><i class="fa fa-sign-out fa-fw"></i> 退出系统</a>
      </li>
    </ul>
    <!-- /.dropdown-user -->
  </li>
  <!-- /.dropdown -->
</ul>
<!-- /.navbar-top-links -->

    <div class="navbar-default sidebar" role="navigation">
      <div class="sidebar-nav navbar-collapse">
        <ul class="nav" id="side-menu">
  <li>
    <a href="#"><i class="fa fa-asterisk fa-fw"></i> 产品管理<span class="fa arrow"></span></a>
    <ul class="nav nav-second-level">
      <li>
        <a href="/manage/activity-list"> 产品查询</a>
      </li>
      <li>
        <a href="/manage/manage-organizer-render-activity"> 产品显示控制</a>
      </li>
    </ul>
    <!-- /.nav-second-level -->
  </li>
  <li>
    <a href="/#"><i class="fa fa-male fa-fw"></i> 报名管理<span class="fa arrow"></span></a>
    <ul class="nav nav-second-level">
      <li>
        <a href="/manage/player-list"> 报名查询</a>
      </li>
    </ul>
  </li>
  <li>
    <a href="#"><i class="fa fa-list-alt fa-fw"></i> 订单管理<span class="fa arrow"></span></a>
    <ul class="nav nav-second-level">
      <li>
        <a href="/manage/order-list"> 订单查询</a>
      </li>
      <li>
        <a href="/manage/refund-list"> 退款管理</a>
      </li>
    </ul>
    <!-- /.nav-second-level -->
  </li>
  <li>
    <a href="#"><i class="fa fa-check-circle fa-fw"></i> 主办方认证<span class="fa arrow"></span></a>
    <ul class="nav nav-second-level">
      <li>
        <a href="/manage/organizer-edit"> 创建主办方</a>
      </li>
      <li>
        <a href="/manage/organizer-list"> 主办方列表</a>
      </li>
      <li>
        <a href="/manage/organizer-print"> 冬令营打印设置</a>
      </li>

    </ul>
    <!-- /.nav-second-level -->
  </li>
  <li>
    <a href="#"><i class="fa fa-picture-o fa-fw"></i> 雪场管理<span class="fa arrow"></span></a>
    <ul class="nav nav-second-level">
      <li>
        <a href="/manage/ski-field-edit"> 创建雪场</a>
      </li>
      <li>
        <a href="/manage/ski-field-list"> 雪场列表</a>
      </li>

    </ul>
    <!-- /.nav-second-level -->
  </li>
  <li>
    <a href="#"><i class="fa fa-users fa-fw"></i> 教练管理<span class="fa arrow"></span></a>
    <ul class="nav nav-second-level">
      <li>
        <a href="/manage/coach-list"> 预约情况</a>
      </li>
    </ul>
    <!-- /.nav-second-level -->
  </li>
  <li>
    <a href="#"><i class="fa fa-credit-card fa-fw"></i> 结算管理<span class="fa arrow"></span></a>
    <ul class="nav nav-second-level">
      <li>
        <a href="/manage/manage-transfer-list"> 转账管理</a>
      </li>
      <li>
        <a href="/manage/manage-withdrawals-apply-list"> 提现申请</a>
      </li>
      <li>
        <a href="/manage/manage-withdrawals-record-list"> 结算列表</a>
      </li>
    </ul>
    <!-- /.nav-second-level -->
  </li>
  <li>
    <a href="#"><i class="fa fa-rmb fa-fw"></i> 财务管理<span class="fa arrow"></span></a>
    <ul class="nav nav-second-level">
      <li>
        <a href="/manage/stream-list"> 交易流水</a>
      </li>
      <li>
        <a href="/manage/manage-bill-record-list"> 对账列表</a>
      </li>
    </ul>
    <!-- /.nav-second-level -->
  </li>
  <li>
    <a href="#"><i class="fa fa-dollar fa-fw"></i> 营销管理<span class="fa arrow"></span></a>
    <ul class="nav nav-second-level">
      <li>
        <a href="/manage/marketing-list"> 返利管理</a>
      </li>
    </ul>
    <!-- /.nav-second-level -->
  </li>
  <li>
    <a href="#"><i class="fa fa-comments fa-fw"></i> 评价管理<span class="fa arrow"></span></a>
    <ul class="nav nav-second-level">
      <li>
        <a href="/manage/comment-list">评价管理</a>
      </li>
    </ul>
  </li>
  <li>
    <a href="#"><i class="fa fa-tasks fa-fw"></i> 定时处理管理<span class="fa arrow"></span></a>
    <ul class="nav nav-second-level">
      <li>
        <a href="/manage/quartz-list"> 定时处理列表</a>
      </li>
    </ul>
    <!-- /.nav-second-level -->
  </li>
  <li>
    <a href="#"><i class="fa fa-wechat fa-fw"></i> 微信页面管理<span class="fa arrow"></span></a>
    <ul class="nav nav-second-level">
      <li>
        <a href="/manage/typography-list"> 微信首页管理</a>
      </li>
      <li>
        <a href="/manage/activity-weight-manage"> 活动置顶</a>
      </li>
    </ul>
    <!-- /.nav-second-level -->
  </li>
</ul>
      </div>
      <!-- /.sidebar-collapse -->
    </div>
    <!-- /.navbar-static-side -->
  </nav>

  <div id="page-wrapper">
    <input type="hidden" id="message-content" value='${filterRuler(activity.typeId,"episode_detail_charge_message")!""}'/>
    <div class="row">
      <div class="col-lg-12">
        <h3 class="page-header">
          ${filterRuler(activity.typeId,"episode_detail_title_head")!""}
          <span class="subtitle">（${activity.title}）</span>
          <#if episode??>
            <#if episode.status == 0>
              <span class="label label-info font-small">
            <#elseif episode.status == 1>
              <span class="label label-success font-small">
            <#elseif episode.status == 2>
              <span class="label label-warning font-small">
            <#elseif episode.status == 3>
              <span class="label label-default font-small">
            <#elseif episode.status == 4>
              <span class="label label-info font-small">
            <#elseif episode.status == 5>
              <span class="label label-danger font-small">
            </#if>
            ${filterRuler(episode.status,"episode")!''}</span>
          </#if>
        </h3>
      </div>
    </div>
    <!-- /.row -->

    <div class="row">
      <div class="col-lg-6">
        <form id="episode-edit-form" role="form">
          <div class="form-group">
            <label class="control-label">名称：</label>
            <input type="text" class="form-control input-sm" name="episode-real-name" id="episode-real-name" placeholder="请输入名称，可不填"
                   style="width: 340px;">
          </div>

          <div class="form-group form-require" id="city-select-div">
            <label class="control-label">地点：</label>

            <div class="form-inline">
              <label class="radio-inline">
                <input id="china-select" name="locationType" type="radio" checked>国内
              </label>
              <label class="radio-inline">
                <input id="nation-select" name="locationType" type="radio">国外
              </label>
            </div>
            <div class="form-inline" id="city-select-area">
              <select class="form-control input-sm" name="provinceId" id="province_id"></select>
              <select class="form-control input-sm" name="cityId" id="city_id"></select>
              <select class="form-control input-sm" name="districtId" id="district_id"></select>
            </div>
            <div class="form-inline" style="display: none;" id="nation-select-area">
              <select id="select-nation"></select>
            </div>
          </div>

          <div class="form-group form-require">
            <label class="control-label">详细地址：</label>
            <input type="text" class="form-control input-sm" name="location" id="episode-location" placeholder="请输入详细地址"
                   style="width: 340px;">
          </div>

          <div class="form-group">
            <label class="control-label">联系人电话：</label>
            <input type="text" class="form-control input-sm" name="notice-phone" id="episode-phone" placeholder="请输入联系人手机号或座机号，可不填"
                   style="width: 340px;">
            <p class="help-block font-small">座机号格式如：010-84549822。若填写，本场的详情页面将显示该联系电话。<br>若不填，则系统默认设为“主办方的联系电话”。</p>
          </div>

          <div class="form-group">
            <label class="control-label">联系人邮箱：</label>
            <input type="text" class="form-control input-sm" name="notice-email" id="episode-email" placeholder="请输入联系人邮箱，可不填"
                   style="width: 340px;">
            <p class="help-block font-small">若填写，本产品的邮件通知将发送到该邮箱。<br>若不填，则系统默认设为“主办方的邮箱地址”。</p>
          </div>

          <div class="form-group form-require">
            <label class="control-label">人数：</label>

            <div class="form-inline">
              <label class="radio-inline">
                <input class="player-limit" id="player-limit-no" name="player-limit" type="radio" value="0" checked>不限人数
              </label>
              <label class="radio-inline">
                <input class="player-limit" id="player-limit-yes" name="player-limit" type="radio" value="1">限制人数
              </label>
              <input id="player-limit-count" name="playerLimitCount" class="form-control input-sm" type="text"
                     maxlength="6" placeholder="请输入人数上限" data-relate="player-limit" style="display: none;">
              <#if episode?? && (episode.status == 1 || episode.status == 2 || episode.status == 5)>
              <p class="help-block font-small">已报名${episode.playerCount}人</p>
              </#if>
            </div>
          </div>

          <div class="form-group form-require">
            <label class="control-label">产品期间：</label>

            <div class="input-group" id="date-range" style="width: 300px;">
              <span class="input-group-addon">
                <i class="glyphicon glyphicon-calendar fa fa-calendar"></i>
              </span>
              <input type="text" class="form-control input-sm" name="timeRange" readonly placeholder="产品开始时间 ~ 产品结束时间"
                     style="width: 300px;">
            </div>
            <input type="hidden" id="start-time" name="startTime">
            <input type="hidden" id="end-time" name="endTime">
            <p class="help-block font-small">注意，发布后，产品期间不可更改。</p>
          </div>
          <#if activity.typeId == 2>
          <div class="form-group form-require">
            <label class="control-label">预约提前时间：</label>

            <div class="form-inline">
              <label class="radio-inline">
                <input id="advance-booking-type-day" name="advance-booking-type" type="radio" value="day">天
              </label>
              <label class="radio-inline">
                <input id="advance-booking-type-hour" name="advance-booking-type" type="radio" value="hour">小时
              </label>
              &nbsp;&nbsp;&nbsp;
              <input id="advance-booking-time" name="advance-booking-time" class="form-control input-sm" type="text"
                     maxlength="6" placeholder="请输入提前时间" data-relate="player-limit" style="width: 110px;">&nbsp;<span id="advance-booking-unit"></span>
              <p class="help-block font-small">注意，发布后，预约提前时间不可更改。默认为提前一天。</p>
            </div>
          </div>
          </#if>

          <div class="form-group">
            <label class="control-label">报名开始时间：</label>
            <div class="form-inline">
              <div class="input-group" id="register-start" style="width: 150px;">
                <span class="input-group-addon">
                  <i class="glyphicon glyphicon-calendar fa fa-calendar"></i>
                </span>
                <input type="text" class="form-control input-sm" readonly placeholder="请选择报名开始时间，可不填" style="width: 180px;">
              </div>
              <span>
                &nbsp;
                <i id="clear-register-start-time" class="fa fa-trash" style="cursor: pointer;"></i>
              </span>
            </div>
            <input type="hidden" id="register-start-time" name="registerStart">
            <p class="help-block font-small">注意，发布后，报名开始时间不可更改。<br>报名开始时间不能大于报名截止时间。</p>
          </div>

          <div class="form-group form-require">
            <label class="control-label">报名截止时间：</label>

            <div class="input-group" id="register-deadline" style="width: 150px;">
              <span class="input-group-addon">
                <i class="glyphicon glyphicon-calendar fa fa-calendar"></i>
              </span>
              <input type="text" class="form-control input-sm" readonly placeholder="请选择报名截止时间" style="width: 180px;">
            </div>
            <input type="hidden" id="register-end-time" name="registerDeadline">
            <p class="help-block font-small">注意，发布后，报名截止时间不可更改。<br>报名截止时间不能大于产品结束时间。</p>
          </div>

          <div class="form-group form-require">
            <label class="control-label">报名是否需要邀请码：</label>

            <div class="form-inline">
              <label class="radio-inline">
                <input id="invite-code-no" name="invite-code" type="radio" checked>不需要
              </label>
              <label class="radio-inline">
                <input id="invite-code-yes" name="invite-code" type="radio">需要
              </label>
              <input type="text" class="form-control input-sm" id="invite-code" size="4" readonly
                     style="display: none; width: 100px; color: red;">
            </div>

            <p class="help-block font-small">
              注意，如果设置了需要邀请码，则没有邀请码，将不能报名。
              <br>您可以将邀请码分享给指定报名人。<br>发布后，邀请码不可更改。
            </p>
          </div>

          <div class="form-group form-require">
            <label>报名成功后是否支持取消报名：</label>

            <div class="form-inline">
              <label class="radio-inline">
                <input id="can-refund-no" name="can-refund" type="radio" value="0" checked>不可取消
              </label>
              <label class="radio-inline">
                <input id="can-refund-yes" name="can-refund" type="radio" value="1">可取消
              </label>

              <div class="input-group" id="refund-deadline" style="width: 150px; display: none;">
                <span class="input-group-addon">
                  <i class="glyphicon glyphicon-calendar fa fa-calendar"></i>
                </span>
                <input type="text" class="form-control input-sm" readonly placeholder="请选择取消报名截止时间"
                       style="width: 155px;">
              </div>
              <input type="hidden" id="refund-time" name="refundDeadline">
            </div>
            <p class="help-block font-small">注意，如果设置了取消报名截止时间，付费项目将进入退款流程。<br>取消报名截止时间不能小于报名截止时间。<br>发布后，不可更改。</p>
          </div>

        </form>
          <div class="form-group">
            <label id="episode-title">${filterRuler(activity.typeId,"episode_detail_intro")!''}：</label>
            <!-- style给定宽度可以影响编辑器的最终宽度 -->
            <p class="help-block font-small">
              注意，请只输入${filterRuler(activity.typeId,"episode_detail_title_head")!''}，通用信息请写到详情中。</p>
            <!--<textarea name="note" id="episode-note" class="form-control" cols="30" rows="8" style="resize: none;"></textarea>-->

            <div class="row">
              <div style="width: 400px;float: left;height: auto;">
                <script type="text/plain" id="episode-note" style="height:240px;"></script>
              </div>

              <div style="float: left;height: auto;">
                <div id="activity-design" class="activity-design clearfix" style="position: absolute;top: 680px;left: 430px;z-index: 999;display: none;">
                  <div class="app-preview">
                    <div class="app-header"></div>
                    <div class="app-entry">
                      <div class="app-config js-config-region">
                        <div class="app-field clearfix editing">
                          <h1 class="page-title"><span>手机预览</span></h1>
                          <div class="control-group">
                            <div class="custom-title text-left">
                              <h2 class="title" id="richtext-title">场次特别说明</h2>
                            </div>
                          </div>
                          <div class="control-group">
                            <div class="custom-richtext" id="richtext-box">
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- Modal -->
<div class="modal fade" id="activity-preview" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
        <h4 class="modal-title" id="myModalLabel">产品手机版二维码</h4>
      </div>
      <div class="modal-body" style="padding-left: 145px;">
        <img src="/server/r/static/images/qrcode.png" style="width: 300px;height: 300px;">
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
      </div>
    </div>
    <!-- /.modal-content -->
  </div>
  <!-- /.modal-dialog -->
</div>
<!-- /.modal -->

      </div>
      <div class="col-lg-6">
        <div class="panel panel-success">
          <div class="panel-heading">
            <span class="form-require">${filterRuler(activity.typeId,"episode_detail_charge_type")!''}</span>

            <div class="pull-right">
              <#if activity.typeId?string != "2">
                <a id="popup-charge-type-view" href="javascript:void(0);" type="button"
                 class="btn btn-primary btn-xs">${filterRuler(activity.typeId,"episode_detail_charge_btn")!''}</a>
              <#else>
                <a id="popup-save-charge-rules" href="javascript:void(0);" type="button"
                   class="btn btn-primary btn-xs">${filterRuler(activity.typeId,"episode_detail_charge_btn")!''}</a>
                <a id="clean-charge-rules" href="javascript:void(0);" type="button"
                   class="btn btn-danger btn-xs" style="display: none;">清空规则</a>
              </#if>
            </div>
          </div>

          <!-- Modal -->
          <div class="modal fade" id="charge-type" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
               aria-hidden="true">
            <div class="modal-dialog">
              <div class="modal-content">
                <div class="modal-header">
                  <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                  <h4 class="modal-title">${filterRuler(activity.typeId,"episode_detail_charge_btn")!''}</h4>
                </div>
                <div class="modal-body">
                  <form id="charge-edit-form" role="form">
                    <div class="form-group" style="padding-left: 100px;">
                      <div class="form-group form-inline form-require">
                        <label class="control-label">${filterRuler(activity.typeId,"episode_detail_charge_name")!''}：</label>
                        <input id="tmp-charge-index" type="hidden"/>
                        <input id="tmp-charge-id" type="hidden"/>

                        <input class="form-control input-sm" id="charge-title" name="chargeTitle" maxlength="30"
                               type="text" placeholder='请输入${filterRuler(activity.typeId, "episode_detail_charge_name")!""}'
                        style="width: 180px;">

                        <p class="help-block font-small">
                          ${filterRuler(activity.typeId,"episode_detail_charge_name")!''}最多为30个字
                        </p>
                      </div>
                      <div class="form-group form-inline form-require">
                        <label class="control-label">价格：</label>
                        <input class="form-control input-sm" id="charge-price" name="chargePrice" type="text"
                               maxlength="8" placeholder="请输入价格" style="width: 100px;">

                        <p class="help-block font-small">单位：元</p>
                      </div>
                      <#if activity.typeId?string == "3">
                      <div class="form-group form-inline form-require">
                        <label class="control-label">商品ID：</label>
                        <input class="form-control input-sm" id="charge-alias" name="chargeAlias" type="text"
                               maxlength="15" placeholder="请输入商品ID" style="width: 140px;">

                        <p class="help-block font-small">第三方系统提供的商品ID</p>
                      </div>
                      </#if>

                      <#if activity.typeId?string != "3">
                        <div class="form-group form-inline form-require">
                          <label class="control-label">购买限制：</label>
                          <label class="radio-inline">
                            <input name="set-buy-limit" id="buy-limit-no" type="radio" value="0" checked>不限
                          </label>
                          <label class="radio-inline">
                            <input name="set-buy-limit" id="buy-limit-yes" value="1" type="radio">限制
                          </label>
                          <input class="form-control input-sm" maxlength="6" id="buy-limit" name="buyLimit"
                                 type="text" data-relate="set-buy-limit" style="display:none; width: 120px;"
                                 placeholder="请输入限购数量">
                          <p class="help-block font-small">
                            对于一个票种来说 ，一个微信用户限购几张票
                          </p>
                        </div>
                      </#if>
                      <div class="form-group form-inline form-require">
                        <label class="control-label">数量限制：</label>
                        <label class="radio-inline">
                          <input name="set-charge-limit" id="charge-limit-no" type="radio" value="0" checked>不限
                        </label>
                        <label class="radio-inline">
                          <input name="set-charge-limit" id="charge-limit-yes" value="1" type="radio">限制
                        </label>
                        <input class="form-control input-sm" maxlength="6" id="charge-limit" name="chargeLimit"
                               type="text" data-relate="set-charge-limit" style="display:none; width: 120px;"
                               placeholder="请输入数量上限">
                        <#if episode?? && (episode.status == 1 || episode.status == 2 || episode.status == 5)>
                        <p class="help-block font-small">已售出<span id="current-charge-count"></span>张</p>
                        </#if>
                      </div>

                    </div>
                  </form>
                </div>
                <div class="modal-footer">
                  <a id="charge-server-update-btn" href="javascript:void(0);" type="button"
                     class="btn btn-success" style="display: none;">修改并保存</a>

                  <a id="charge-create-btn" href="javascript:void(0);" type="button" class="btn btn-success">添加</a>
                  <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                </div>
              </div>
              <!-- /.modal-content -->
            </div>
            <!-- /.modal-dialog -->
          </div>
          <!-- /.modal -->

          <!-- Modal -->
          <div class="modal fade" id="charge-rules-table" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
               aria-hidden="true">
            <div class="modal-dialog" style="width: 90%;">
              <div class="modal-content">
                <div class="modal-header">
                  <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                  <h4 class="modal-title">教练教学价格</h4>
                </div>
                <div class="modal-body">
                  <form role="form">
                    <div class="form-group">
                      <table class="table table-bordered" id="charge-rules-table-content">
                      </table>
                    </div>
                  </form>
                </div>
                <div class="modal-footer">
                  <a id="charge-rules-table-update-btn" href="javascript:void(0);" type="button" class="btn btn-success">保存</a>
                  <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                </div>
              </div>
              <!-- /.modal-content -->
            </div>
            <!-- /.modal-dialog -->
          </div>
          <!-- /.modal -->

          <!-- /.panel-heading -->
          <div class="panel-body" id="charge-area">
            <#if activity.typeId?string != "2">
            <form role="form-group">
              <table class="table table-striped table-bordered table-hover">
                <thead>
                <tr class="no-wrap warning">
                  <th>No.</th>
                  <th>${filterRuler(activity.typeId,"episode_detail_charge_name")!''}</th>
                  <th>价格</th>
                  <#if activity.typeId?string == "3">
                  <th>商品ID</th>
                  </#if>
                  <th>购买限制</th>
                  <th>数量限制</th>
                  <th>操作</th>
                </tr>
                </thead>
                <tbody id="charge-list"></tbody>
              </table>
              <p class="help-block font-small">注意，已售出的票的名称和价格将不能更改。</p>
            </form>
            <#else>

            </#if>
          </div>
          <!-- /.panel-body -->
        </div>
        <!-- /.panel -->
        <#if activity.typeId?string != "3">
        <div class="panel panel-success">
          <div class="panel-heading">
            <span class="form-require">报名表</span>
          </div>

          <!-- /.panel-heading -->
          <div class="panel-body">
            <#if activity.typeId?string != "5">
              <div class="form-group">
                <div>可选：</div>
                <div class="btn-group" id="player-optional-info" role="group"></div>
              </div>
              <div class="form-group">
                <div>自定义：</div>
                <div class="btn-group" id="player-customer-info" role="group">
                  <button type="button" class="btn btn-warning btn-outline btn-sm " data-type="text">+单行文本框</button>
                  <button type="button" class="btn btn-warning btn-outline btn-sm " data-type="textarea">+多行文本框</button>
                  <button type="button" class="btn btn-warning btn-outline btn-sm " data-type="select">+下拉选择框</button>
                </div>
              </div>
              <hr>
              <div class="form-group" id="optional-items">
              </div>
              <hr>
              <div class="form-group has-warning" id="customer-items">
              </div>
              <p class="help-block font-small">注意，发布后，报名表不可更改。</p>
            <#else>
              <div class="form-group">
                <div>可选：</div>
                <div class="btn-group" id="player-optional-info" role="group"></div>
              </div>
              <hr>
              <div class="form-group" id="optional-items">
              </div>
              <p class="help-block font-small">注意，发布后，报名表不可更改。</p>
            </#if>
          </div>
          <!-- /.panel-body -->
        </div>
        <!-- /.panel -->
        </#if>

        <div class="panel">
          <label class="control-label">上传产品群组二维码：</label>
          <input type="hidden" id="episode-wechatGroupUrl"/>
          <table class="table">
            <tr>
              <td id="img-uploader">
                <img src="" alt="" id="preview-image" style="margin: 20px 0px;" width="150" height="150">

                <div id="filePicker">选择图片</div>
              </td>
              <td class="font-small">
                <p>获取微信群二维码的方法：</p>

                <p>1. 如果没有微信群，请创建一个微信群</p>

                <p>2. 进入群聊界面，点击右上角的人像，进入“聊天信息”界面，点击“群二维码”</p>

                <p>3. 在“群二维码名片”，点击右上角菜单，选择“用邮件分享二维码”</p>

                <p>4. 输入您的邮箱地址，点击“发送”</p>

                <p>5. 用电脑登入邮箱，将收取到的二维码图片右键另存为到本地，上传此图片到本系统</p>

                <p>注意，新生成的微信群二维码将会在7天左右过期，请即使更新。</p>
              </td>
            </tr>
          </table>
        </div>

        <div>
          <a id="episode-save-btn" href="javascript:void(0);" class="btn btn-primary episode-control-btn hidden">创建</a>
          <a id="episode-return-btn" class="btn btn-default episode-control-btn hidden">返回</a>
        </div>

      </div>

    </div>

    <!-- /#page-wrapper -->

  </div>
  <!-- /#wrapper -->
  <script id="tpl-item-text" type="text/template">
    <div class="form-group" id="render-item-{{id}}">
      <label class="control-label">{{title}}</label>
      <% if (editMode == 0 || editMode == 1 ) { %>
      <i class="fa fa-close" onclick="hxz.removeItem(this);"></i>
      <% } %>
      <input type="text" class="form-control" data-id="{{id}}" placeholder="{{placeHolder}}">
    </div>
  </script>

  <script id="tpl-item-textarea" type="text/template">
    <div class="form-group" id="render-item-{{id}}">
      <label class="control-label">{{title}}</label>
      <% if (editMode == 0 || editMode == 1 ) { %>
      <i class="fa fa-close" onclick="hxz.removeItem(this);"></i>
      <% } %>
      <textarea class="form-control" data-id="{{id}}" rows="3" placeholder="{{placeHolder}}"></textarea>
    </div>
  </script>

  <script id="tpl-item-select" type="text/template">
    <div class="form-group" id="render-item-{{id}}">
      <label class="control-label">{{title}}</label>
      <% if (editMode == 0 || editMode == 1 ) { %>
      <i class="fa fa-close" onclick="hxz.removeItem(this);"></i>
      <% } %>
      <select class="form-control" data-id="{{id}}">
        <% _.each(values, function(item, index) { %>
        <option value="{{item.key}}">{{item.value}}</option>
        <% }) %>
      </select>
    </div>
  </script>

  <script id="tpl-item-file" type="text/template">
    <div class="form-group" id="render-item-{{id}}">
      <label class="control-label">{{title}}</label>
      <% if (editMode == 0 || editMode == 1 ) { %>
      <i class="fa fa-close" onclick="hxz.removeItem(this);"></i>
      <% } %>
      <input type="text" class="form-control" data-id="{{id}}" placeholder="{{placeHolder}}" readonly>
    </div>
  </script>

  <script id="tpl-customer-item-text" type="text/template">
    <div class="form-group customer-player-meta" data-id="{{id}}" data-type="text">
      <label class="control-label">单行文本框</label>
      <% if (editMode == 0 || editMode == 1 ) { %>
      <i class="fa fa-close" onclick="hxz.removeItem(this);"></i>
      <% } %>
      <div class="form-group">
        <label class="control-label">
          <input class="form-control" type="text" name="title" placeholder="单行文本框：项目名称" value="{{title}}">
        </label>
        <input type="text" class="form-control" name="placeholder" placeholder="单行文本框：提示信息" value="{{placeHolder}}">
      </div>
    </div>
  </script>

  <script id="tpl-customer-item-textarea" type="text/template">
    <div class="form-group customer-player-meta" data-id="{{id}}" data-type="textarea">
      <label class="control-label">多行文本框</label>
      <% if (editMode == 0 || editMode == 1 ) { %>
      <i class="fa fa-close" onclick="hxz.removeItem(this);"></i>
      <% } %>
      <div class="form-group">
        <label class="control-label">
          <input class="form-control" type="text" name="title" placeholder="多行文本框：项目名称" value="{{title}}">
        </label>
        <input type="text" class="form-control" name="placeholder" placeholder="多行文本框：提示信息" value="{{placeHolder}}">
      </div>
    </div>
  </script>

  <script id="tpl-customer-item-select" type="text/template">
    <div class="form-group customer-player-meta" data-id="{{id}}" data-type="select">
      <label class="control-label">下拉选择框</label>
      <% if (editMode == 0 || editMode == 1 ) { %>
      <i class="fa fa-close" onclick="hxz.removeItem(this);"></i>
      <% } %>
      <div class="form-group select-option-group">
        <label class="control-label">
          <input class="form-control" type="text" name="title" placeholder="下拉选择框：项目名称" value="{{title}}">
        </label>
        <% _.each(values, function(item, index) { %>
        <div class="row select-option">
          <div class="col-xs-1">
            <% if (index == 0) { %>
            <i class="fa fa-plus-square-o fa-2x edit-control-icon" onclick="hxz.addSelectOption(this);"></i></div>
          <% } else { %>
          <i class="fa fa-minus-square-o fa-2x edit-control-icon" onclick="hxz.removeSelectOption(this);"></i></div>
        <% } %>
        <div class="col-xs-11">
          <input class="form-control" type="text" name="option" placeholder="选项" value="{{item.value}}">
        </div>
      </div>
      <% }) %>
    </div>
    </div>
  </script>

  <script id="tpl-charge-list-item" type="text/template">
    <tr>
      <td>{{ chargeIndex }}</td>
      <td>{{ chargeName }}</td>
      <td>{{ price }}元</td>
      <#if activity.typeId?string == "3">
      <td>{{ alias }}</td>
      </#if>
      <td>{{ buyLimitDisplay  }}</td>
      <td>{{ chargeLimitDisplay }}</td>
      <td>
        <% if (editMode == 0 || editMode == 1 || editMode == 2) { %>
          <a href="javascript:void(0);" type="button" class="btn btn-primary btn-xs charge-edit" data-charge-index="{{ chargeIndex }}">编辑</a>
        <% } %>
        <% if (editMode == 0 || editMode == 1) { %>
          <a href="javascript:void(0);" type="button" class="btn btn-danger btn-xs charge-del" data-charge-index="{{ chargeIndex }}">删除</a>
        <% } %>
        <% if (editMode == 3 || editMode == 2) { %>
          <% if (valid == 1) { %>
            <a href="javascript:void(0);" type="button" class="btn btn-danger btn-xs charge-stop" data-charge-index="{{ chargeIndex }}">暂停购买</a>
          <% } else { %>
            <a href="javascript:void(0);" type="button" class="btn btn-success btn-xs charge-start" data-charge-index="{{ chargeIndex }}">开放购买</a>
          <% } %>
        <% } %>
      </td>
    </tr>
  </script>

  <script id="tpl-charge-rules" type="text/template">
    <% _.each(rules, function(rule, pId) { %>
    <div class="form-group" id="rule-title-{{pId}}">
      <label class="control-label">
        {{rule.name}}
      </label>
      <div class="checkbox">
        <label>
          <input class="charge-rules-no-check" data-pid="{{pId}}" type="checkbox" value="all">不选择
        </label>
      </div>
      <div class="checkbox">
        <% _.each(rule.children, function(name, id) { %>
        <label>
          <input class="charge-rules-item charge-rules-{{pId}}-item" name="{{name}}" type="checkbox" value="{{id}}">{{name}}
        </label>
        <% }) %>
      </div>
    </div>
    <% }) %>
  </script>

  <div id="hxz-background" class="background" style="display: none; "></div>
<div id="hxz-progressBar" class="progressBar" style="display: none; ">数据加载中，请稍等...</div>

<script src="/server/r/require.js"></script>
<script>/*resourcemap*/
require.config({paths:{
  "r/bower_components/underscore/underscore-min": "/server/r/bower_components/underscore/underscore-min",
  "r/bower_components/jquery/dist/jquery.min": "/server/r/bower_components/jquery/dist/jquery.min",
  "r/static/js/hxz/hxz.valid": "/server/r/static/js/hxz/hxz.valid_12cc206",
  "r/static/js/hxz/hxz.rest": "/server/r/static/js/hxz/hxz.rest_07c8105",
  "r/bower_components/alertify/alertify.min": "/server/r/bower_components/alertify/alertify.min",
  "r/static/js/alertify-config": "/server/r/static/js/alertify-config_0cc8db2",
  "r/bower_components/bootstrap/dist/js/bootstrap.min": "/server/r/bower_components/bootstrap/dist/js/bootstrap.min",
  "r/bower_components/metisMenu/dist/metisMenu.min": "/server/r/bower_components/metisMenu/dist/metisMenu.min",
  "r/bower_components/select2/dist/js/select2": "/server/r/bower_components/select2/dist/js/select2",
  "r/static/js/hxz/hxz.ui": "/server/r/static/js/hxz/hxz.ui_0a7714d",
  "r/static/js/hxz/hxz": "/server/r/static/js/hxz/hxz_589b155",
  "r/vendor/umeditor/umeditor.config": "/server/r/vendor/umeditor/umeditor.config",
  "r/vendor/umeditor/umeditor": "/server/r/vendor/umeditor/umeditor",
  "r/vendor/umeditor/lang/zh-cn/zh-cn": "/server/r/vendor/umeditor/lang/zh-cn/zh-cn",
  "r/bower_components/moment/min/moment-with-zh-cn.min": "/server/r/bower_components/moment/min/moment-with-zh-cn.min",
  "r/bower_components/fex-webuploader/dist/webuploader": "/server/r/bower_components/fex-webuploader/dist/webuploader",
  "r/static/js/data/other-player-meta": "/server/r/static/js/data/other-player-meta_2394801",
  "r/bower_components/bootstrap-daterangepicker/daterangepicker": "/server/r/bower_components/bootstrap-daterangepicker/daterangepicker",
  "r/bower_components/jquery-validation/dist/jquery.validate.min": "/server/r/bower_components/jquery-validation/dist/jquery.validate.min"
}});

    var nationData = ${nationData};
    window.UMEDITOR_HOME_URL = "../server/r/vendor/umeditor/";
    window.imageUrl = "/manage/ue/upload.json"
  

    require(["r/bower_components/underscore/underscore-min", "r/static/js/hxz/hxz", "r/vendor/umeditor/lang/zh-cn/zh-cn", "r/static/js/alertify-config", "r/bower_components/moment/min/moment-with-zh-cn.min", "r/bower_components/fex-webuploader/dist/webuploader", "r/static/js/data/other-player-meta", "r/bower_components/select2/dist/js/select2", "r/bower_components/bootstrap-daterangepicker/daterangepicker", "r/bower_components/jquery-validation/dist/jquery.validate.min"], function (_, hxz, UM, alertify, moment, WebUploader, otherPlayerMeta) {

      var tmpChargeList = [];
      var tmpChargeRules = [];

      var episodeNote = UM.getEditor('episode-note');
      $("#activity-design").hide();

      episodeNote.addListener('focus', function () {
        $("#activity-design").show();
        $("#richtext-title").html($("#episode-title").html());
        $("#richtext-box").html(episodeNote.getContent());
      });

      episodeNote.addListener('blur', function () {
        $("#activity-design").hide();
      });

      episodeNote.addListener('contentchange', function () {
        $("#richtext-box").html(episodeNote.getContent());
      });

      var regionType = "china";

      var selectedOtherPlayerInfo = [];
      // 只保存选中的player meta id
      var selectedPlayerInfo = {};

      var customerPlayerInfo = [];
      var customerItemId = 0;

      var ajaxbg = $("#hxz-background,#hxz-progressBar");

      var activityId = $('#activity-id').val();
      var activityTypeId = $('#activity-type-id').val();
      var episodeId = $("#episode-id").val();
      var episodeStatus = $('#episode-status').val();
      var currentPlayerCount = $('#current-player-count').val();
      var episodeMetaName = $('#episode-meta-name').val();

      var $voucherSend = $('#voucher-send');

      // 编辑模式判断
      // 0 创建，1 编辑，2 暂停时编辑，3 部分编辑
      var editMode = 0;
      if (episodeId && episodeId != '') {
        if (episodeStatus == 0) {
          editMode = 1;
        } else if (episodeStatus == 5) {
          editMode = 2;
        } else {
          editMode = 3;
        }
      }

      var $saveBtn = $('#episode-save-btn');

      // 场次名称、手机号、邮箱
      var $episodeRealName = $('#episode-real-name');
      var $episodeNoticePhone = $('#episode-phone');
      var $episodeNoticeEmail = $('#episode-email');

      // 行政区划
      var $province = $('#province_id');
      var $city = $('#city_id');
      var $district = $('#district_id');
      // 详细地址
      var $location = $('#episode-location');
      //教练预约 提前时间
      var $advanceBookingTypeDay = $('#advance-booking-type-day');
      var $advanceBookingTypeHour = $('#advance-booking-type-hour');
      var $advanceBookingTime = $('#advance-booking-time');
      var advanceBookingType = 'day';

      // 人数
      var $playerLimitNo = $('#player-limit-no');
      var $playerLimitYes = $('#player-limit-yes');
      var $playerLimitCount = $('#player-limit-count');

      // 时间
      var $dateRange = $('#date-range');
      var $dateRangeInput = $('#date-range input');
      var $registerStart = $('#register-start');
      var $registerStartInput = $('#register-start input');
      var $registerEnd = $('#register-deadline');
      var $registerEndInput = $('#register-deadline input');

      var $regionChina = $("#china-select");
      var $regionNation = $("#nation-select");

      var $startTime = $('#start-time');
      var $endTime = $('#end-time');
      var $registerStartTime = $('#register-start-time');
      var $registerEndTime = $('#register-end-time');

      // 邀请码
      var $inviteCodeNo = $('#invite-code-no');
      var $inviteCodeYes = $('#invite-code-yes');
      var $inviteCode = $('#invite-code');

      // 退款
      var $canRefundNo = $('#can-refund-no');
      var $canRefundYes = $('#can-refund-yes');

      // 退款截止时间
      var $refundDate = $('#refund-deadline');
      var $refundDateInput = $('#refund-deadline input');

      var $refundTime = $('#refund-time');

      // 添加票种

      // 不是教练预约
      if (activityTypeId != 2) {

        // 保存规则，生成charge表格
        var $addCharge = $('#popup-charge-type-view');
        // 票券表
        var $chargeList = $('#charge-list');

        // 票名
        var $chargeTitle = $('#charge-title');
        // 票价
        var $chargePrice = $('#charge-price');
        // 票的别名：一般不显示，对于雪票，用来存在易程电子码
        var $chargeAlias = $('#charge-alias');

        // 票数
        var $chargeLimitNo = $('#charge-limit-no');
        var $chargeLimitYes = $('#charge-limit-yes');
        var $chargeLimit = $('#charge-limit');

        //限购张数
        // 票数
        var $buyLimitNo = $('#buy-limit-no');
        var $buyLimitYes = $('#buy-limit-yes');
        var $buyLimit = $('#buy-limit');

      } else {
        var $generateCharge = $('#popup-save-charge-rules');
        var $cleanCharge = $('#clean-charge-rules');
      }

      // 行政区划 start
      var getRegionByPrarentId = function (parentId, callback) {
        hxz.doGet({url: hxz.RestApi.regionListByParentId + "?parentId=" + parentId}, function (o) {
          if (o.status == 1) {
            callback(o.data);
          }
        });
      };

      var renderProvince = function () {
        //console.log('****** loading province ******');
        getRegionByPrarentId(1, function (data) {
          //console.log('****** FINISH province ******');
          var html = '<option value="none" selected disabled>请选择省份/直辖市</option>';
          $.each(data, function (index, r) {
            html += '<option value="' + r.regionId + '">' + r.province + '</option>';
          });
          $province.empty().append(html);
        });
      };

      var renderCity = function (provinceId, defaultCityId, defaultDistrictId) {
        //console.log('****** loading city ******');
        getRegionByPrarentId(provinceId, function (data) {
          //console.log('****** FINISH city ******');
          var html = '<option value="none" selected disabled>请选择城市</option>';
          var flag = false;
          $.each(data, function (index, r) {
            // 直辖市处理
            if (r.district) {
              flag = true;
              html = '<option value="' + provinceId + '">' + r.city + '</option>';
              return false;
            }
            html += '<option value="' + r.regionId + '">' + r.city + '</option>';
          });
          $city.empty().append(html);
          if (defaultCityId) {
            $province.val(provinceId);
            $city.val(defaultCityId);
          }

          if (flag) {
            // 如果是直辖市、直接用当前数据查找区
            _renderDistrict(data, provinceId, defaultDistrictId);
          } else if (defaultCityId) {
            // 如果有默认cityId、直接查找区
            renderDistrict(defaultCityId, defaultDistrictId);
          } else {
            $district.empty().append('<option value="none" selected disabled>请先选择县/地区</option>');
          }
        });
      };

      var _renderDistrict = function (data, cityId, defaultDistrictId) {
        var html = '<option value="none" selected disabled>请选择县/地区</option>';
        $.each(data, function (index, r) {
          html += '<option value="' + r.regionId + '">' + r.district + '</option>';
        });
        $district.empty().append(html);
        if (defaultDistrictId) {
          $district.val(defaultDistrictId);
        }
      };

      var renderDistrict = function (cityId, defaultDistrictId) {
        //console.log('****** loading district ******');
        getRegionByPrarentId(cityId, function (data) {
          //console.log('****** FINISH district ******');
          _renderDistrict(data, cityId, defaultDistrictId);
        });
      };

      var bindRegion = function () {
        renderProvince();
        $province.on('change', function (e) {
          var $t = $(e.currentTarget);
          var id = $t.val();
          if (id !== 'none') {
            renderCity(id);
          }
        });
        $city.on('change', function (e) {
          var $t = $(e.currentTarget);
          var id = $t.val();
          if (id !== 'none') {
            renderDistrict(id);
          }
        });
      };
      // 行政区划 end

      // 各种事件
      var Events = function () {

        $city.append('<option value="none" selected disabled>请先选择城市</option>');
        $district.append('<option value="none" selected disabled>请先选择县/地区</option>');
        bindRegion();

        // 人数限制
        $playerLimitNo.click(function () {
          $playerLimitCount.val('').hide();
        });

        $playerLimitYes.click(function () {
          $playerLimitCount.show();
        });

        $advanceBookingTypeDay.click(function () {
          $("#advance-booking-unit").html("天");
          advanceBookingType = "day";
        });

        $advanceBookingTypeHour.click(function () {
          $("#advance-booking-unit").html("小时");
          advanceBookingType = "hour";
        });

        $regionChina.click(function () {
          regionType = "china";
          $("#city-select-area").show();
          $("#nation-select-area").hide();
        });

        $regionNation.click(function () {
          regionType = "nation";
          $("#city-select-area").hide();
          $("#nation-select-area").show();
        });

        // 邀请码
        $inviteCodeNo.click(function () {
          $inviteCode.val('').hide();
        });

        $inviteCodeYes.click(function (e, defaultCode) {
          var code = defaultCode || generateRandom(4);
          $inviteCode.val(code).show();
        });

        // 退款
        $canRefundNo.click(function () {
          $refundTime.val('');
          $refundDate.hide();
        });

        $canRefundYes.click(function () {
          $refundDate.show();
        });

      };

      var pageInit = function () {

        ajaxbg.hide();
        // 各种事件绑定
        Events();

        $("#select-nation").select2({
          language: "zh-CN",
          placeholder: "请选择国家",
          width: "200",
          data: nationData
        });

        // 不是教练预约
        if (activityTypeId != 2) {
          chargeEvents();
        } else {
          $advanceBookingTypeDay.trigger('click');
          $advanceBookingTime.val(1);
          chargeRulesEvents();
        }

        // 时间
        if (editMode != 2 && editMode != 3) {
          var commDateConfig = {
            minDate: new Date(),
            startDate: new Date(),
            timePicker: true,
            timePickerIncrement: 1,
            timePicker24Hour: true,
            locale: {
              format: 'YYYY年MM月DD日',
              separator: ' - ',
              applyLabel: '确定',
              cancelLabel: '关闭',
              weekLabel: 'W',
              customRangeLabel: 'Custom Range',
              daysOfWeek: moment.weekdaysMin(),
              monthNames: moment.monthsShort(),
              firstDay: moment.localeData().firstDayOfWeek()
            }
          };
          $dateRange.daterangepicker(commDateConfig, function (start, end, label) {
            $dateRangeInput.val(hxz.datetime(start) + ' ~ ' + hxz.datetime(end));
            // start 和 end 是moment对象
            var sDate = new Date(start);
            var eDate = new Date(end);
            $startTime.val(sDate.getTime());
            $endTime.val(eDate.getTime());
            //console.log(sDate.getTime());
            //console.log(eDate.getTime());
          });

          commDateConfig.singleDatePicker = true;

          $registerStart.daterangepicker(commDateConfig, function (start, end, label) {
            $registerStartInput.val(hxz.datetime(start));
            var date = new Date(start);
            $registerStartTime.val(date.getTime());
          });

          $registerEnd.daterangepicker(commDateConfig, function (start, end, label) {
            $registerEndInput.val(hxz.datetime(start));
            var date = new Date(start);
            $registerEndTime.val(date.getTime());
          });

          $refundDate.daterangepicker(commDateConfig, function (start, end, label) {
            $refundDateInput.val(hxz.datetime(start));
            var date = new Date(start);
            $refundTime.val(date.getTime());
          });
          //清空报名开始时间
          $("#clear-register-start-time").click(function () {
            $registerStartInput.val("");
            $registerStartTime.val("");
          });
        }

        // 文件上传 start
        // 初始化Web Uploader
        var uploader = WebUploader.create({
          // 选完文件后，是否自动上传。
          auto: true,
          // swf文件路径
          swf: "../server/r/bower_components/fex-webuploader/dist/Uploader.swf",
          // 文件接收服务端。
          server: "http://image.huaxuezoo.com/upload",
          // 选择文件的按钮。可选。
          // 内部根据当前运行是创建，可能是input元素，也可能是flash.
          pick: {
            id: "#filePicker",
            multiple: false
          },
          // 只允许选择图片文件。
          accept: {
            title: "Images",
            extensions: "gif,jpg,jpeg,bmp,png",
            mimeTypes: "image/*"
          },
          thumb: {
            width: 110,
            height: 110,
            // 图片质量，只有type为`image/jpeg`的时候才有效。
            quality: 70,
            // 是否允许放大，如果想要生成小图的时候不失真，此选项应该设置为false.
            allowMagnify: false,
            // 是否允许裁剪。
            crop: true,
            // 为空的话则保留原有图片格式。
            // 否则强制转换成指定的类型。
            type: "image/jpeg"
          },
          compress: {
            width: 150,
            height: 150,
            // 图片质量，只有type为`image/jpeg`的时候才有效。
            quality: 90,
            // 是否允许放大，如果想要生成小图的时候不失真，此选项应该设置为false.
            allowMagnify: false,
            // 是否允许裁剪。
            crop: true,
            // 是否保留头部meta信息。
            preserveHeaders: true,
            // 如果发现压缩后文件大小比原来还大，则使用原来图片
            // 此属性可能会影响图片自动纠正功能
            noCompressIfLarger: true,
            // 单位字节，如果图片大小小于此值，不会采用压缩。
            compressSize: 0
          }
        });

        // 当有文件添加进来的时候
        uploader.on('fileQueued', function (file) {
          ajaxbg.show();
          uploader.makeThumb(file, function (error, src) {
            if (error) {
              $("#preview-image").replaceWith('<span>不能预览</span>');
              return;
            }

            $("#preview-image").attr("src", src);
          }, 150, 150);
        });

        // 文件上传成功，给item添加成功class, 用样式标记上传成功。
        uploader.on('uploadSuccess', function (file, response) {
          ajaxbg.hide();
          $("#episode-wechatGroupUrl").val(response[0].url);
        });
        // 文件上传 end

        if (editMode != 0) {
          // 编辑场次
          $saveBtn.text('更新');
          fetchEpisodeDetail(episodeId);
        } else {
          // 创建场次

          // 显示报名表
          renderPlayerForm();
        }

        // 显示操作按钮
        $('.episode-control-btn').removeClass('hidden');

      };

      // 通用禁止
      function setDisabled(targets) {
        $.each(targets, function (index, target) {
          target.attr('disabled', 'disabled');
        });
      }

      // 进入编辑画面，获得场次详细信息
      function fetchEpisodeDetail(episodeId) {

        hxz.doGet({url: hxz.RestApi.manageEpisodeDetail + "?episodeId=" + episodeId}, function (o) {

          //console.log("fetchEpisodeDetail");
          //console.log(o);

          if (o.status == 1) {

            var data = o.data;
            // 场次名称
            $episodeRealName.val(data.name);
            $episodeNoticePhone.val(data.noticePhone);
            $episodeNoticeEmail.val(data.noticeEmail);

            if (o.data.cityId === o.data.provinceId && o.data.cityId === o.data.districtId) {
              $("#nation-select").trigger("click");
              $("#select-nation").val(o.data.cityId).trigger("change");
            } else {
              // 设定行政区划值
              renderCity(data.provinceId, data.cityId, data.districtId);
            }
            // 详细地址
            $location.val(data.location);

            if (data.playerLimit > 0) {
              $playerLimitYes.trigger('click');
            } else {
              $playerLimitNo.trigger('click');
            }

            if (data.advanceBookingType == 'day') {
              $advanceBookingTypeDay.trigger('click');
              $advanceBookingTime.val(data.advanceBookingTime);
            } else if (data.advanceBookingType == 'hour') {
              $advanceBookingTypeHour.trigger('click');
              $advanceBookingTime.val(data.advanceBookingTime);
            }
            $playerLimitCount.val(data.playerLimit);

            // 产品时间
            if (editMode != 2 && editMode != 3) {
              var drp = $dateRange.data('daterangepicker');
              drp.setStartDate(new Date(data.startTime));
              drp.setEndDate(new Date(data.endTime));
            }
            $dateRangeInput.val(hxz.datetime(data.startTime) + ' ~ ' + hxz.datetime(data.endTime));

            $startTime.val(data.startTime);
            $endTime.val(data.endTime);

            // 报名开始时间
            if (data.registerStart) {
              if (editMode != 2 && editMode != 3) {
                $registerStart.data('daterangepicker').setStartDate(new Date(data.registerStart));
              }
              $registerStartInput.val(hxz.datetime(data.registerStart));
              $registerStartTime.val(data.registerStart);
            }

            // 报名截止时间
            if (editMode != 2 && editMode != 3) {
              $registerEnd.data('daterangepicker').setStartDate(new Date(data.registerDeadline));
            }
            $registerEndInput.val(hxz.datetime(data.registerDeadline));
            $registerEndTime.val(data.registerDeadline);

            // 邀请码
            if (data.inviteCode && data.inviteCode.length > 0) {
              $inviteCodeYes.trigger('click', data.inviteCode);
            }

            // 退款
            if (data.refundDeadline) {
              $canRefundYes.trigger('click');
              if (editMode != 2 && editMode != 3) {
                $refundDate.data('daterangepicker').setStartDate(new Date(data.refundDeadline));
              }
              $refundDateInput.val(hxz.datetime(data.refundDeadline));

              $refundTime.val(data.refundDeadline);
            }

            // 场次特别说明
            episodeNote.setContent(data.note);

            // 显示产品群组二维码 图片
            $("#preview-image").attr("src", data.wechatGroupUrl);

            tmpChargeList = data.charges;
            // 不是教练预约
            if (activityTypeId != 2) {
              renderChargeList();
            }

            //生成报名表信息 start
            var playerMetaJson = $.parseJSON(data.playerMeta);
            $.each(playerMetaJson, function (index, p) {
              selectedPlayerInfo[p.id] = p;
            });
            renderPlayerForm();

            if (editMode == 2) {
              // 禁止编辑
              var targets = [$regionChina, $regionNation, $inviteCodeNo, $advanceBookingTypeDay, $advanceBookingTypeHour, $advanceBookingTime, $inviteCodeYes, $inviteCode, $canRefundNo, $canRefundYes];
              // 不是教练预约
              if (activityTypeId != 2) {
                targets.push($chargeTitle, $chargePrice, $chargeAlias);
              } else {
                $cleanCharge.hide();
              }
              setDisabled(targets);
            } else if (editMode == 3) {
              // 禁止编辑
              var targets = [$province, $city, $district, $location, $advanceBookingTypeDay, $advanceBookingTypeHour, $advanceBookingTime, $playerLimitNo, $playerLimitYes, $playerLimitCount, $regionChina, $regionNation, $inviteCodeNo, $inviteCodeYes, $inviteCode, $canRefundNo, $canRefundYes, $("#select-nation")];
              // 不是教练预约
              if (activityTypeId != 2) {
                targets.push($chargeTitle, $chargePrice, $chargeAlias);
                $addCharge.hide();
              } else {
                $cleanCharge.hide();
              }
              setDisabled(targets);

            }
          }
        });
      }

      function generateRandom(length) {

        var charactors = "1234567890";
        var value = "", i;
        for (var j = 1; j <= length; j++) {
          i = parseInt(10 * Math.random());
          value = value + charactors.charAt(i);
        }
        return value;
      }

      function renderChargeList() {

        var tpl = _.template($("#tpl-charge-list-item").html());
        var html = '';

        for (var i in tmpChargeList) {

          var _data = tmpChargeList[i];

          _data.chargeIndex = (Number(i) + 1);

          _data.editMode = editMode;


          if (_data.chargeLimit == 0) {
            _data.chargeLimitDisplay = '不限';
          } else {
            _data.chargeLimitDisplay = _data.chargeLimit;
          }

          if (_data.buyLimitCount == 0) {
            _data.buyLimitDisplay = '不限';
          } else {
            _data.buyLimitDisplay = _data.buyLimitCount;
          }

          html += tpl(_data);
        }

        $chargeList.empty().append(html);
      }

      var otherInfo = {};
      // 冬令营
      if (activityTypeId == "5") {
        otherInfo = otherPlayerMeta.camp;
      } else {
        otherInfo = otherPlayerMeta.normal;
      }
      //console.log(otherInfo);
      // 生成报名表
      function renderPlayerForm() {
        var $oi = $("#player-optional-info").html("");
        var html = '';
        for (var i in otherInfo) {
          var id = (otherInfo[i].displayId) ? otherInfo[i].displayId : i;
          var title = (otherInfo[i].displayTitle) ? otherInfo[i].displayTitle : otherInfo[i].title;
          html += '<button type="button" class="btn btn-success btn-outline btn-sm optional-player-meta" id="' + id + '"data-index=' + i + '>' + title + '</button>';
        }
        $oi.append(html);
        playerFormEvent();

        // 除雪票外，报名表都显示姓名和手机
        $("#player-optional-info #real_name").trigger('click');
        $("#player-optional-info #phone").trigger('click');
        // 且不能删除
        $("#render-item-real_name .fa-close").remove();
        $("#render-item-phone .fa-close").remove();

        // 显示已经设定的表单项
        $.each(selectedPlayerInfo, function (key, value) {
          var r1 = /^customer-player-meta-(\d+)$/;
          var r2 = /^##camp_player_info/;
          if (r1.test(key) && !r2.test(value.title)) {
            var num = key.match(r1)[1];
            customerItemId = num + 1;
            $('button[data-type="' + value.type + '"]').trigger('click', value);
          } else {
            var id = (value.displayId) ? (value.displayId) : key;
            if (id == "email") {
              $('#player-optional-info #' + id).trigger('click', ["load"]);
            } else {
              $('#player-optional-info #' + id).trigger('click');
            }
          }
        });

        if (editMode == 2 || editMode == 3) {
          // 解除绑定
          $("#player-optional-info").off("click");
          $("#player-customer-info").off("click");
        }
      }

      function playerFormEvent() {

        var $optional = $('#optional-items');
        var $customer = $('#customer-items');
        // 选择表单项：可选
        $("#player-optional-info").on("click", ".btn", function (e, a) {

          var $t = $(e.currentTarget);
          // 防止重复添加
          if ($t.hasClass('active')) return;

          var tData = otherInfo[$t.data('index')];

          var targetData = {
            id: (tData.displayId) ? tData.displayId : tData.id,
            title: (tData.displayTitle) ? tData.displayTitle : tData.title,
            editMode: editMode,
            type: tData.type,
            values: tData.values,
            placeHolder: tData.placeHolder
          };

          $t.removeClass('btn-outline').addClass('active');

          var render = _.template($('#tpl-item-' + targetData.type).html());

          var html = render(targetData);

          // 证件类型 和 证件号 绑定
          if (targetData.id == 'id_card_no') {
            $('#player-optional-info #id_card_type').trigger('click');
            $optional.append(html);
          } else if (targetData.id == 'id_card_type') {
            $optional.append(html);
            $('#player-optional-info #id_card_no').trigger('click');
          } else {
            $optional.append(html);
          }

          if (targetData.id == 'email' && !a) {

            alertify.confirm("确认启用向报名人发送报名凭证功能？", function (event) {
              // 取消
              if (!event) return;

              $voucherSend.val(1);
              $('#render-item-email input').attr('placeholder', '邮箱（向参加人发送报名凭证）');
            });
          }
        });
        // 选择表单项：自定义
        $("#player-customer-info").on("click", ".btn", function (e, params) {
          var $t = $(e.currentTarget);
          var type = $t.data('type');
          var render = _.template(($('#tpl-customer-item-' + type).html()));
          customerItemId++;

          var data = {};
          // 已有数据初始化
          if (params) {
            data = params;
          } else {
            data = {
              id: "customer-player-meta-" + customerItemId,
              title: "",
              placeHolder: ""
            };
            if (type == 'select') {
              data.values = [{key: 'option-0', value: ''}];
            }
          }
          data.editMode = editMode;
          $customer.append(render(data));
        });

      }

      // 使用jquery validate 验证部分表单值
      $.validator.setDefaults({
        ignore: ''
      });

      // episode 所有check 规则
      var r_episode = {
        location: {
          rules: {
            required: true
          },
          messages: {
            required: "详细地址不能为空"
          }
        },
        playerLimitCount: {
          rules: {
            digits: true,
            radioCheck: true
          },
          messages: {
            digits: "只能输入数字",
            radioCheck: "人数上限不能为空"
          }
        },
        // 对应editMode==2
        playerLimitCount2: {
          rules: {
            digits: true,
            radioCheck: true,
            moreThanCurrentPlayerCount: true
          },
          messages: {
            digits: "只能输入数字",
            radioCheck: "人数上限不能为空",
            moreThanCurrentPlayerCount: "人数上限不能小于已报名人数"
          }
        },
        startTime: {
          rules: {
            future: true
          },
          messages: {
            future: "开始时间不能小于当前时间"
          }
        },
        endTime: {
          rules: {
            future: true,
            timeRange: true
          },
          messages: {
            future: "结束时间不能小于当前时间",
            timeRange: "开始时间不能大于结束时间"
          }
        },
        registerStart: {
          rules: {
            future: true,
            timeBefore: ['#register-end-time']
          },
          messages: {
            future: "报名开始时间不能小于当前时间",
            timeBefore: "报名开始时间不能大于报名截止时间"
          }
        },
        registerDeadline: {
          rules: {
            future: true,
            timeBefore: ['#end-time']
          },
          messages: {
            future: "报名截止时间不能小于当前时间",
            timeBefore: "报名截止时间不能大于结束时间"
          }
        },
        refundDeadline: {
          rules: {
            refundTimeBefore: true
          },
          messages: {
            refundTimeBefore: "取消报名截止时间不能小于报名截止时间"
          }
        }
      };

      var episode_validate_rules = {};
      var episode_validate_messages = {};
      // editMode == 3时，不走这块的check
      if (editMode == 0 || editMode == 1) {
        episode_validate_rules = {
          location: r_episode.location.rules,
          playerLimitCount: r_episode.playerLimitCount.rules,
          startTime: r_episode.startTime.rules,
          endTime: r_episode.endTime.rules,
          registerDeadline: r_episode.registerDeadline.rules,
          refundDeadline: r_episode.refundDeadline.rules
        };
        episode_validate_messages = {
          location: r_episode.location.messages,
          playerLimitCount: r_episode.playerLimitCount.messages,
          startTime: r_episode.startTime.messages,
          endTime: r_episode.endTime.messages,
          registerDeadline: r_episode.registerDeadline.messages,
          refundDeadline: r_episode.refundDeadline.messages
        };
      } else if (editMode == 2) {
        episode_validate_rules = {
          location: r_episode.location.rules,
          playerLimitCount: r_episode.playerLimitCount2.rules
        };
        episode_validate_messages = {
          location: r_episode.location.messages,
          playerLimitCount: r_episode.playerLimitCount2.messages
        };
      }

      $("#episode-edit-form").validate({
        rules: episode_validate_rules,
        messages: episode_validate_messages,
        submitHandler: function (form) {
          //console.log('通过验证');
          doSubmit();
        }
      });

      $.validator.addMethod("radioCheck", function (value, element, param) {
        var relate = $(element).data('relate');
        // 如果值为1、则该字段必须
        if (parseInt($('input:radio[name="' + relate + '"]:checked').val())) {
          return value.length > 0;
        }
        return true;
      });

      $.validator.addMethod("future", function (value, element, param) {
        // 只有创建时，做check
        if (editMode == 0) {
          var date = new Date();
          var now = date.getTime();
          return (value > now);
        } else {
          return true;
        }
      });

      $.validator.addMethod("timeRange", function (value, element, param) {
        return ($startTime.val() < $endTime.val());
      });

      $.validator.addMethod("timeBefore", function (value, element, param) {
        var limit = $(param[0]).val();
        return (value <= limit);
      });

      $.validator.addMethod("refundTimeBefore", function (value, element, param) {
        // 如果值为1、则该字段必须
        if (parseInt($('input:radio[name="can-refund"]:checked').val())) {
          var registerTime = $registerEndTime.val();
          return (registerTime <= value);
        }
        return true;
      });

      $.validator.addMethod("lessThanPlayerLimit", function (value, element, param) {
        if (parseInt($playerLimitCount.val()) > 0) {
          return (value <= parseInt($playerLimitCount.val()));
        } else {
          return true;
        }
      });

      $.validator.addMethod("moreThanCurrentPlayerCount", function (value, element, param) {
        if (parseInt(currentPlayerCount) > 0 && value > 0) {
          return (value >= parseInt(currentPlayerCount));
        } else {
          return true;
        }
      });

      $.validator.addMethod("moreThanCurrentChargeCount", function (value, element, param) {
        if (parseInt($('#current-charge-count').text()) > 0 && value > 0) {
          return (value >= parseInt($('#current-charge-count').text()));
        } else {
          return true;
        }
      });

      // 场次创建 或 修改
      $("#episode-save-btn").on("click", function () {

        // 如果设定了报名开始，则增加验证
        if ($registerStartTime.val()) {
          $registerStartTime.rules("add", {
            future: true,
            timeBefore: ['#register-end-time'],
            messages: {
              future: "报名开始时间不能小于当前时间",
              timeBefore: "报名开始时间不能大于报名截止时间"
            }
          });
        }
        $("#episode-edit-form").submit();

      });

      function chargeRulesEvents() {

        // rules的顺序是固定的：日期(date)、人数(number)、时长(duration)
        var rulesKeyMap = ['date', 'number', 'duration'];
        var parentRules = {};
        var tmpTmpChargeRules = [];

        // 已有数据
        if (tmpChargeList.length > 0) {
          // btn名修改：生成规则 -> 查看规则
          $generateCharge.text('查看规则');
          $cleanCharge.show();
        }

        hxz.doGet({url: hxz.RestApi.manageChargeRules}, function (o) {
          if (o.status == 1) {

            var tpl = _.template($("#tpl-charge-rules").html());

            var data = {
              rules: o.data
            };

            var ti = 0;
            $.each(o.data, function (pid, value) {
              parentRules[rulesKeyMap[ti]] = {name: value.name, id: pid};
              ti++;
            });


            var html = tpl(data);
            $('#charge-area').append(html);

            // 不选择规则
            $('.charge-rules-no-check').click(function (e) {
              var $t = $(e.currentTarget);

              var $item = $('.charge-rules-' + $t.data('pid') + '-item');
              if (!$t.is(':checked')) {
                // 将该规则下的checkbox设为可选
                $item.removeAttr('disabled');
              } else {
                // 将该规则下的checkbox设为不可选
                $item.attr('checked', false).attr('disabled', 'disabled');
              }
            });
          }
        });

        // 除创建外，都请求已创建的规则
        if (editMode != 0) {
          // btn名修改：生成规则 -> 查看规则
          $generateCharge.text('查看规则');
          $cleanCharge.show();

          hxz.doGet({url: hxz.RestApi.manageCheckedChargeRules + "?episodeId=" + episodeId}, function (o) {
            if (o.status == 1) {
              $.each(o.data, function (index, value) {
                // 选择
                $('.charge-rules-item[value="' + value + '"]').attr("checked", "checked");
              });
              $('#charge-area input:checkbox').attr('disabled', 'disabled');
            }
          });
        }

        var renderChargeRuleTable = function () {
          var checkedRules = {};
          tmpTmpChargeRules = [];

          $.each(parentRules, function (key, pRule) {
            var length = 0;
            if (typeof(checkedRules[key]) == 'undefined') {
              checkedRules[key] = {
                id: pRule.id,
                name: pRule.name,
                children: {}
              };
            }
            var $checked = $('.charge-rules-' + pRule.id + '-item:checked');
            $.each($checked, function (index, t) {
              length++;
              checkedRules[key]["children"][t.value] = t.name;
            });
            checkedRules[key]["clength"] = length;
          });
          //console.log(checkedRules);

          var rules = checkedRules;
          var da = rules.date;
          var nu = rules.number;
          var ti = rules.duration;

          if (da.clength == 0 && nu.clength == 0 && ti.clength == 0) {
            alertify.log("请选择相关规则");
            return;
          }

          // 存入tmpTmpChargeRules
          if (da.clength > 0) {
            $.each(da.children, function (id, name) {
              tmpTmpChargeRules.push(id);
            });
          }
          if (nu.clength > 0) {
            $.each(nu.children, function (id, name) {
              tmpTmpChargeRules.push(id);
            });
          }
          if (ti.clength > 0) {
            $.each(ti.children, function (id, name) {
              tmpTmpChargeRules.push(id);
            });
          }
          //console.log(tmpTmpChargeRules);

          var renderTable = function (checkedRules) {

            $('#charge-rules-table-content').empty();

            var headrowspan = 1;
            if (da.clength == 0) {
              headrowspan = 2;
            }

            // 列信息
            var colInfo = [];

            // table header第一行
            var rowOne = "<th>" + ti.name + "</th>";

            if (ti.clength == 0) {
              rowOne += "<th colspan='" + da.clength + "'>不限时长</th>";
            } else {
              $.each(ti.children, function (id, name) {
                rowOne += "<th style='vertical-align:middle' colspan='" + da.clength + "' rowspan='" + headrowspan + "'>" + name + "</th>"
              });
            }

            rowOne = "<tr class='warning'>" + rowOne + "</tr>";

            var renderRowTwo = function (tiId, tiName) {
              var rowTwo = "";
              if (da.clength == 0) {
                var date = {
                  id: da.id,
                  name: da.name
                };
                var duration = {
                  id: tiId,
                  name: tiName
                };
                colInfo.push({date: date, duration: duration});
              } else {
                $.each(da.children, function (daId, daName) {
                  rowTwo += "<th>" + daName + "</th>";
                  var date = {
                    id: daId,
                    name: daName
                  };
                  var duration = {
                    id: tiId,
                    name: tiName
                  };
                  colInfo.push({date: date, duration: duration});
                });
              }
              return rowTwo;
            };

            // table header第二行
            var rowTwo = "<th>" + nu.name + "</th>";

            if (ti.clength == 0) {
              rowTwo += renderRowTwo(ti.id, ti.name);
            } else {
              $.each(ti.children, function (tiId, tiName) {
                rowTwo += renderRowTwo(tiId, tiName);
              });
            }

            rowTwo = "<tr class='warning'>" + rowTwo + "</tr>";

            var otherAttr = "";
            if (editMode == 2 || editMode == 3) {
              otherAttr = "disabled";
            }

            var renderTbodyRow = function (row, nuId, nuName) {
              $.each(colInfo, function (index, value) {
                // rules的顺序是固定的：日期(date)、人数(number)、时长(duration)
                var chargeAlias = value.date.id + '-' + nuId + '-' + value.duration.id;
                var chargeName = value.date.name + '-' + nuName + '-' + value.duration.name;
                row += "<td><input style='max-width:60px;' type='text' data-charge-alias='" + chargeAlias + "' id='charge-rule-index-" + chargeIndex + "' data-charge-name='" + chargeName + "' placeholder='价格：元' " + otherAttr + "></td>";
                chargeIndex++;
              });
              row = "<tr>" + row + "</tr>";
              return row;
            };

            // table body
            var bodyRows = '';

            var chargeIndex = 0;
            if (nu.clength == 0) {
              var row = "<td class='warning'>任意人数</td>";
              bodyRows += renderTbodyRow(row, nu.id, nu.name);
            } else {
              $.each(nu.children, function (nuId, nuName) {
                var row = "<td class='warning'>" + nuName + "</td>";
                bodyRows += renderTbodyRow(row, nuId, nuName);
              });
            }

            var thead = "<thead>" + rowOne + rowTwo + "</thead>";
            var tbody = "<tbody>" + bodyRows + "</tbody>";
            $('#charge-rules-table-content').append(thead + tbody);

          };

          // 生成表格
          renderTable(checkedRules);
          // 已有charge数据的时候，显示价格
          if (tmpChargeList.length > 0) {
            $.each(tmpChargeList, function (index, c) {
              $('#charge-rule-index-' + index).val(c.price).attr('data-charge-id', c.chargeId).attr('data-has-saved', 'true');
            });
          }

          // 隐藏保存按钮
          if (editMode == 2 || editMode == 3) {
            $('#charge-rules-table-update-btn').hide();
          }

          $("#charge-rules-table").modal("show");
        };

        // 生成或查看table
        $generateCharge.on("click", function () {
          renderChargeRuleTable();
        });

        // 模态窗口关闭时触发
        $("#charge-rules-table").on('hidden.bs.modal', function (e) {

        });

        // 保存或修改价格
        $("#charge-rules-table-update-btn").on("click", function () {
          // 存入tmpChargeRules
          tmpChargeRules = tmpTmpChargeRules;
          //console.log(tmpChargeRules);
          var hasErr = false;
          // 存入tmpChargeList
          $('#charge-rules-table-content input:text').each(function (index, c) {
            var $c = $(c);
            var chargeId = $c.data('charge-id') || '';
            var chargeName = $c.data('charge-name');
            var price = $c.val();
            var alias = $c.data('charge-alias');
            var hasSaved = $c.data('has-saved');

            if (!price) {
              alertify.log('请输入“' + chargeName + '”的价格');
              hasErr = true;
              return false;
            }

            if (isNaN(price)) {
              alertify.log('“' + chargeName + '”的价格必须为数字');
              hasErr = true;
              return false;
            }

            if (hasSaved == true) {
              // 修改
              var tmpCharge = tmpChargeList[index];
              tmpCharge.chargeId = chargeId;
              tmpCharge.chargeName = chargeName;
              tmpCharge.price = price;
              tmpCharge.alias = alias;
              tmpCharge.chargeLimit = 0;
            } else {
              // 添加
              tmpChargeList.push({
                chargeId: chargeId,
                chargeName: chargeName,
                price: price,
                alias: alias,
                // 默认chargeCount为0
                chargeCount: 0,
                chargeLimit: 0
              });
            }
          });
          //console.log(tmpChargeList);

          // 正常生成charge数据
          if (!hasErr && tmpChargeList.length > 0) {
            // 禁用所有规则选择
            $('#charge-area input:checkbox').attr('disabled', 'disabled');
            // btn名修改：生成规则 -> 查看规则
            $generateCharge.text('查看规则');
            $cleanCharge.show();
            $("#charge-rules-table").modal("hide");
          }
        });

        // 清空规则
        $cleanCharge.on('click', function () {
          alertify.confirm("确认要清空规则吗？", function (event) {

            // 点击确认
            if (event) {

              // 不是创建 清空后端已保存的数据
              if (editMode != 0) {
                hxz.doGet({url: hxz.RestApi.manageChargeRulesDelete + "?episodeId=" + episodeId}, function (o) {
                  if (o.status == "1") {
                    alertify.log(o.msg);
                  } else if (o.status == "0") {
                    alertify.log(o.msg);
                  }
                }, function (err) {
                  alertify.log("系统错误");
                });
              }

              tmpChargeList = [];
              tmpChargeRules = [];

              $('#charge-area input:checkbox').attr('checked', false).removeAttr('disabled');

              // btn名修改：查看规则 -> 生成规则
              $generateCharge.text('生成规则');
              $cleanCharge.hide();
            }
          });
        });

      }

      function chargeEvents() {

        $chargeLimitNo.on("click", function () {
          $chargeLimit.val('').hide();
        });

        $chargeLimitYes.on("click", function () {
          $chargeLimit.show();
        });


        $buyLimitNo.on("click", function () {
          $buyLimit.val('').hide();
        });

        $buyLimitYes.on("click", function () {
          $buyLimit.show();
        });

        // 票券编辑
        $chargeList.on("click", ".charge-edit", function (e) {

          var chargeIndex = $(e.currentTarget).data("charge-index");
          var _c = _.find(tmpChargeList, function (obj) {
            return obj.chargeIndex == chargeIndex
          });

          $chargeLimit.val(_c.chargeLimit || "");

          $buyLimit.val(_c.buyLimitCount || "");

          if (_c.chargeLimit > 0) {
            $chargeLimitYes.trigger('click');
          } else {
            $chargeLimitNo.trigger('click');
          }

          if (_c.buyLimitType > 0) {
            $buyLimitYes.trigger('click');
          } else {
            $buyLimitNo.trigger('click');
          }

          $chargePrice.val(_c.price);
          $chargeTitle.val(_c.chargeName);
          $chargeAlias.val(_c.alias);

          // 已购买票数
          $('#current-charge-count').text(_c.chargeCount);

          // 可能有下单 未支付的
          if (_c.chargeCount == 0) {
            // 暂停编辑时，放开限制
            //$chargeTitle.removeAttr("disabled");
            //$chargePrice.removeAttr("disabled");
            //$chargeAlias.removeAttr("disabled");
          }
          // 如果存在id
          $("#tmp-charge-id").val(_c.chargeId || "");
          $("#tmp-charge-index").val(_c.chargeIndex);

          $("#charge-create-btn").html("修改");
          $("#charge-type").modal("show");

        });
        // 票券删除
        $chargeList.on("click", ".charge-del", function (e) {

          var chargeIndex = $(e.currentTarget).data("charge-index");

          var _c = _.find(tmpChargeList, function (obj) {
            return obj.chargeIndex == chargeIndex
          });

          var afterDeleteCharge = function () {
            // 删除前台的临时数据
            tmpChargeList = _.reject(tmpChargeList, function (obj) {
              return obj.chargeIndex == chargeIndex
            });
            // 重绘
            renderChargeList();
          };

          alertify.confirm("确认删除吗？", function (event) {

            // 点击确认
            if (event) {

              if (_c && _c.chargeId) {
                // 对于已保存的数据，删除后台已经保存的数据

                var chargeDeleteData = {
                  chargeId: _c.chargeId
                };

                hxz.doPost({url: hxz.RestApi.manageChargeDelete, data: chargeDeleteData}, function (data) {
                  if (data.status == "1") {
                    alertify.log(data.msg);
                    afterDeleteCharge();
                  } else if (data.status == "0") {
                    alertify.log(data.msg);
                  }
                }, function (err) {
                  alertify.log("系统错误");
                });

              } else {
                // 对于前台保存的数据
                afterDeleteCharge();
              }

            }
          });
        });

        // 票券继续报名
        $chargeList.on("click", ".charge-start", function (e) {
          var chargeIndex = $(e.currentTarget).data("charge-index");
          var _c = _.find(tmpChargeList, function (obj) {
            return obj.chargeIndex == chargeIndex
          });
          alertify.confirm("确认开放购买吗？", function (event) {
            // 点击确认
            if (event) {
              if (_c && _c.chargeId) {
                // 对于已保存的数据，删除后台已经保存的数据
                hxz.doPost({url: hxz.RestApi.manageChargeStart + "?chargeId=" + _c.chargeId}, function (data) {
                  if (data.status == "1") {
                    alertify.log(data.msg);
                    _c.valid = 1;
                    renderChargeList();
                  } else if (data.status == "0") {
                    alertify.log(data.msg);
                  }
                }, function (err) {
                  alertify.log("系统错误");
                });
              }
            }
          });
        });

        // 票券暂停报名
        $chargeList.on("click", ".charge-stop", function (e) {
          var chargeIndex = $(e.currentTarget).data("charge-index");
          var _c = _.find(tmpChargeList, function (obj) {
            return obj.chargeIndex == chargeIndex
          });

          var startedChargeCount = 0;
          _.each(tmpChargeList, function (obj) {
            if (obj.valid == 1) {
              startedChargeCount++;
            }
          });
          if (startedChargeCount == 1) {
            alertify.error("请至少保证一种票在售。<br>若要暂停全部票种，请暂停场次。");
            return;
          }

          alertify.confirm("确认暂停购买吗？", function (event) {
            // 点击确认
            if (event) {
              if (_c && _c.chargeId) {
                // 对于已保存的数据，删除后台已经保存的数据
                hxz.doPost({url: hxz.RestApi.manageChargeStop + "?chargeId=" + _c.chargeId}, function (data) {
                  if (data.status == "1") {
                    alertify.log(data.msg);
                    _c.valid = 0;
                    renderChargeList();
                  } else if (data.status == "0") {
                    alertify.log(data.msg);
                  }
                }, function (err) {
                  alertify.log("系统错误");
                });
              }
            }
          });
        });

        // 票券创建、修改
        $("#charge-create-btn").on("click", function () {
          if (editMode == 3) {
            // 暂停时修改
            var postData = {
              "episodeId": episodeId,
              "note": episodeNote.getContent(),
              "wechatGroupUrl": $("#episode-wechatGroupUrl").val()
            };

            if (postData.note && postData.note.length > 5000) {
              return alertify.log("场次特别说明内容过长");
            }
            hxz.doPost({url: "/manage/episode/update.json", data: postData}, function (data) {

              if (data.status == "1") {
                alertify.confirm(data.msg + "，是否离开当前页面？", function (event) {
                  // 确定
                  if (event) {
                    window.location.href = "/manage/activity-detail?activityId=" + activityId;
                  } else {
                    window.location.reload(false);
                  }
                });

              } else if (data.status == "0") {
                return alertify.log(data.msg);
              }
            });

          } else {
            $('#charge-edit-form').submit();
          }

        });

        var saveCharge = function () {
          var chargeId = $("#tmp-charge-id").val();
          var chargeName = $chargeTitle.val();
          var price = Number($chargePrice.val());
          var alias = $chargeAlias.val();
          var chargeLimit = Number($chargeLimit.val());
          var buyLimitType = 0;
          var buyLimitCount = 0;
          if ($buyLimit.val() != '') {
            buyLimitType = 1;
            buyLimitCount = Number($buyLimit.val());
          }

          //判断是否修改
          var tmpChargeIndex = $("#tmp-charge-index").val();

          if (tmpChargeIndex) {
            //修改操作
            var tmpCharge = tmpChargeList[Number(tmpChargeIndex - 1)];
            tmpCharge.chargeId = chargeId;
            tmpCharge.chargeName = chargeName;
            tmpCharge.price = price;
            tmpCharge.alias = alias;
            tmpCharge.chargeLimit = chargeLimit;
            tmpCharge.buyLimitType = buyLimitType;
            tmpCharge.buyLimitCount = buyLimitCount;
          } else {
            //添加操作
            tmpChargeList.push({
              chargeId: chargeId,
              chargeName: chargeName,
              price: price,
              alias: alias,
              // 默认chargeCount为0
              chargeCount: 0,
              chargeLimit: chargeLimit,
              buyLimitType: buyLimitType,
              buyLimitCount: buyLimitCount,
              valid: 1
            });
          }

          //console.log(tmpChargeList);

          renderChargeList();
          $("#charge-type").modal("hide");
        };

        // 开启设定票种窗口
        $addCharge.on("click", function () {

          $chargeLimit.val("");
          $chargePrice.val("");
          $chargeTitle.val("");

          $("#tmp-charge-index").val("");

          //20151020  修复票无法删除导致 不能保存 start
          $("#tmp-charge-id").val("");
          //20151020  修复票无法删除导致 不能保存 end

          // 隐藏售出票数
          $("#current-charge-count").parent().hide();

          // 暂停编辑时，放开限制
          $chargeTitle.removeAttr("disabled");
          $chargePrice.removeAttr("disabled");
          $chargeAlias.removeAttr("disabled");

          $("#charge-create-btn").html("添加");
          $("#charge-type").modal("show");
        });

        var r_charge = {
          chargeTitle: {
            rules: {
              required: true
            },
            messages: {
              required: $("#message-content").val() + "名称不能为空"
            }
          },
          chargePrice: {
            rules: {
              required: true,
              number: true
            },
            messages: {
              required: "价格不能为空",
              number: "只能输入数字"
            }
          },
          chargeAlias4Ticket: {
            rules: {
              required: true,
              number: true
            },
            messages: {
              required: "商品ID不能为空",
              number: "只能输入数字"
            }
          },
          chargeLimit: {
            rules: {
              digits: true,
              lessThanPlayerLimit: true,
              radioCheck: true
            },
            messages: {
              digits: "只能输入数字",
              lessThanPlayerLimit: $("#message-content").val() + "数量不能超过人数上限",
              radioCheck: "数量上限不能为空"
            }
          },
          buyLimit: {
            rules: {
              digits: true,
              lessThanPlayerLimit: true,
              radioCheck: true
            },
            messages: {
              digits: "只能输入数字",
              lessThanPlayerLimit: $("#message-content").val() + "数量不能超过人数上限",
              radioCheck: "数量上限不能为空"
            }
          },
          // 对应editMode==2
          chargeLimit2: {
            rules: {
              digits: true,
              radioCheck: true,
              moreThanCurrentChargeCount: true,
              lessThanPlayerLimit: true
            },
            messages: {
              digits: "只能输入数字",
              radioCheck: "数量上限不能为空",
              moreThanCurrentChargeCount: "数量不能小于已售出的数量",
              lessThanPlayerLimit: $("#message-content").val() + "数量不能超过人数上限"
            }
          }
        };

        var charge_validate_rules = {};
        var charge_validate_messages = {};

        // editMode == 3时，不走这块的check
        if (editMode == 0 || editMode == 1) {
          charge_validate_rules = {
            chargeTitle: r_charge.chargeTitle.rules,
            chargePrice: r_charge.chargePrice.rules,
            chargeLimit: r_charge.chargeLimit.rules,
            buyLimit: r_charge.buyLimit.rules
          };
          charge_validate_messages = {
            chargeTitle: r_charge.chargeTitle.messages,
            chargePrice: r_charge.chargePrice.messages,
            chargeLimit: r_charge.chargeLimit.messages,
            buyLimit: r_charge.buyLimit.messages
          };
        } else if (editMode == 2) {
          charge_validate_rules = {
            chargeTitle: r_charge.chargeTitle.rules,
            chargePrice: r_charge.chargePrice.rules,
            chargeLimit: r_charge.chargeLimit2.rules,
            buyLimit: r_charge.buyLimit.rules
          };
          charge_validate_messages = {
            chargeTitle: r_charge.chargeTitle.messages,
            chargePrice: r_charge.chargePrice.messages,
            chargeLimit: r_charge.chargeLimit2.messages,
            buyLimit: r_charge.buyLimit.messages
          };
        }
        // 对于雪票，需要check电子码
        if (activityTypeId == 3) {
          charge_validate_rules["chargeAlias"] = r_charge.chargeAlias4Ticket.rules;
          charge_validate_messages["chargeAlias"] = r_charge.chargeAlias4Ticket.messages;
        }

        $("#charge-edit-form").validate({
          rules: charge_validate_rules,
          messages: charge_validate_messages,
          submitHandler: function (form) {
            //console.log('通过验证');
            saveCharge();
          }
        });

      }
      function doSubmit() {

        var re_phone = /^\d{11}$/;
        var re_telephone = /^(\d{3,4}\-)?\d{7,8}$/i;
        var re_email = /\w@\w+\.\w/;

        // 追加check start
        if (regionType == "china") {
          if (!$province.val()) {
            return alertify.log("请选择省份/直辖市");
          }

          if (!$city.val()) {
            return alertify.log("请选择城市");
          }

          if (!$district.val()) {
            return alertify.log("请选择县/地区");
          }
        } else {
          if (!$("#select-nation").val()) {
            return alertify.log("请选择国家");
          }
        }
        // 联系人电话
        var noticePhone = $episodeNoticePhone.val();
        if (noticePhone) {
          if (!re_phone.test(noticePhone) && !re_telephone.test(noticePhone)) {
            return alertify.log("联系人电话格式不正确");
          }
        }
        // 联系人邮箱地址
        var noticeEmail = $episodeNoticeEmail.val();
        if (noticeEmail) {
          if (!re_email.test(noticeEmail)) {
            return alertify.log("联系人邮箱格式不正确");
          }
        }
        // 不是教练预约
        if (activityTypeId != 2) {
          if (tmpChargeList.length == 0) {
            return alertify.log("请至少添加一种" + $("#message-content").val());
          }

          var playerLimit = Number($playerLimitCount.val());
          if (playerLimit > 0) {
            var totalCharge = 0;
            var flag = true;
            for (var i = 0; i < tmpChargeList.length; i++) {
              // 如果有票数限制，则所有票数之和不能小于场次人数
              if (tmpChargeList[i].chargeLimit > 0) {
                totalCharge += tmpChargeList[i].chargeLimit;
              } else {
                flag = false;
                break;
              }
            }

            if (flag) {
              if (totalCharge < playerLimit) {
                return alertify.log("所有" + $("#message-content").val() + "数量之和不能小于人数上限");
              }
            }
          }
        } else {
          var bookingTime = $advanceBookingTime.val();
          if (!bookingTime) {
            return alertify.log("请输入预约提前时间");
          } else if (isNaN(parseInt(bookingTime)) || parseInt(bookingTime) != bookingTime || parseInt(bookingTime) < 1) {
            return alertify.log("预约提前时间必须为正整数");
          }
        }
        // 生成selectedOtherPlayerInfo
        $('.optional-player-meta.active').each(function (index, ele) {
          var i = $(ele).data('index');
          selectedOtherPlayerInfo.push(otherInfo[i]);
        });

        // 追加check end

        // 生成自定义用户信息
        // flag: 0 正确，1 项目名称为空，2 下拉框选项为空
        var customerErrFlag = 0;
        $('.customer-player-meta').each(function (index, ele) {
          var $t = $(ele);
          var id = $t.data('id');
          var type = $t.data('type');
          var title = $t.find('[name="title"]').val();
          var placeHolder = $t.find('[name="placeholder"]').val();
          var values = [];

          // 项目名称不能为空
          if (!title) {
            customerErrFlag = 1;
            return false;
          }

          if (type == 'select') {
            var selectFlag = false;
            $t.find('[name="option"]').each(function (index, option) {
              // 选项不能为空
              if (!$(option).val()) {
                selectFlag = true;
                return false;
              }
              values.push({
                "key": "option-" + (index + 1),
                "value": $(option).val()
              });
            });
            if (selectFlag) {
              customerErrFlag = 2;
              return false;
            }
            placeHolder = '';
          }

          var itemData = {
            "id": id,
            "title": title,
            "type": type,
            "values": values,
            "placeHolder": placeHolder
          };

          customerPlayerInfo.push(itemData);
        });
        // 有错误
        if (customerErrFlag == 1) {
          return alertify.log("自定义项目名称不能为空");
        } else if (customerErrFlag == 2) {
          return alertify.log("自定义下拉选择框项的选项不能为空");
        }

        var tmpPlayerMeta = _.union(selectedOtherPlayerInfo, customerPlayerInfo);
        //console.log(tmpPlayerMeta);

        var data = {
          // "episodeId": 1, 判断编辑和修改状态
          "activityId": Number(activityId),
          "name": $episodeRealName.val(),
          "noticePhone": $episodeNoticePhone.val(),
          "noticeEmail": $episodeNoticeEmail.val(),
          "startTime": $startTime.val(),
          "endTime": $endTime.val(),
          "registerStart": $registerStartTime.val(),
          "registerDeadline": $registerEndTime.val(),
          "refundDeadline": $refundTime.val(),
          "provinceId": regionType == "china" ? Number($province.val()) : Number($("#select-nation").val()),
          "cityId": regionType == "china" ? Number($city.val()) : Number($("#select-nation").val()),
          "districtId": regionType == "china" ? Number($district.val()) : Number($("#select-nation").val()),
          "location": $location.val(),
          "advanceBookingType": advanceBookingType,
          "advanceBookingTime": $advanceBookingTime.val(),
          "longitude": "",
          "latitude": "",
          "note": episodeNote.getContent(),
          //playerLimit 需要判断是否限制人数 不限人数为0
          "playerLimit": Number($playerLimitCount.val()),
          "wechatGroupUrl": $("#episode-wechatGroupUrl").val(),
          "inviteCode": $inviteCode.val(),
          "playerMeta": JSON.stringify(tmpPlayerMeta),
          "voucherSend": $voucherSend.val(),
          "editMode": editMode
          //status 状态后台保存
        };

        // 是否退款
        var isPayback = parseInt($('input:radio[name="can-refund"]:checked').val());


        // 是教练预约，乘车chargeRules
        if (activityTypeId == 2) {
          if (tmpChargeRules == 0 && tmpChargeList == 0) {
            return alertify.log("请生成教学价格");
          }

          data.chargeRules = JSON.stringify(tmpChargeRules);
        }

        // 生成chargeList
        for (var i in tmpChargeList) {
          // 设置不可退款
          tmpChargeList[i].isPayback = isPayback;
        }

        data.charges = JSON.stringify(tmpChargeList);


        // 修改操作装入 episodeId;
        if (episodeId && episodeId.length > 0) {
          data.episodeId = Number(episodeId);
        }

        if (data.note && data.note.length > 5000) {
          return alertify.log("场次特别说明内容过长");
        }

        var saveBtnName = $saveBtn.text();

        alertify.confirm("确定" + saveBtnName + episodeMetaName + "？", function (event) {
          if (!event) return;

          hxz.doPost({url: "/manage/episode/save.json", data: data}, function (data) {
            if (data.status == "1") {
              //alertify.confirm(episodeMetaName + saveBtnName + "成功，确定离开当前页面？", function (event) {
              //  // 取消
              //  if (!event) return;

              window.location.href = "/manage/activity-detail?activityId=" + activityId;
              //});

            } else if (data.status == "0") {
              return alertify.log(data.msg);
            }
          });
        });
      }

      $('#episode-return-btn').click(function () {
        alertify.confirm('确定放弃编辑吗？', function (event) {
          // 点击确认
          if (event) {
            window.location.href = "/manage/activity-detail?activityId=" + activityId;
          }
        });
      });

      // 执行页面初始化
      pageInit();

    });
  

    window.onload = function () {

      var global = window.hxz = {};

      global.removeItem = function (t) {
        var $p = $(t).parent('.form-group');
        var id = $p.children('.form-control').data('id');

        // 可选项目
        if (id) {
          // 证件类型 和 证件号 绑定
          if (id == 'id_card_no') {
            $p.prev().remove();
            $('#id_card_type').addClass('btn-outline').removeClass('active');
          } else if (id == 'id_card_type') {
            $p.next().remove();
            $('#id_card_no').addClass('btn-outline').removeClass('active');
          }

          $('#' + id).addClass('btn-outline').removeClass('active');
          // 邮件 删除发送报名凭证
          if (id == 'email') {
            $('#voucher-send').val(0);
          }
        }

        $p.remove();
      };

      global.addSelectOption = function (t) {
        var $p = $(t).parents('.select-option-group');
        $p.append('<div class="row select-option"><div class="col-xs-1"><i class="fa fa-minus-square-o fa-2x edit-control-icon" onclick="hxz.removeSelectOption(this);"></i></div><div class="col-xs-11"><input class="form-control" type="text" name="option" placeholder="选项"></div></div>');
      };

      global.removeSelectOption = function (t) {
        $(t).parents('.select-option').remove();
      };

    }
  </script>
</body>
</html>